`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Module: AUDIO_Beta
// Author: Rui Li & modified by Zhiyuan Lin
// Description: This module can only generate different tunes when different 
//              button pressed.
//////////////////////////////////////////////////////////////////////////////////
module AUDIO_Beta(audio, sys_CLK, button);
	output  audio;
	input   sys_CLK, button;
	reg  [23:0] counter4Hz, counter6MHz;
	reg  [13:0] count, origin;
	reg  audiof;
	reg  clk_6MHz, clk_4Hz;
	reg  [4:0] j;
	reg  [7:0] len;

	assign audio = button? audiof : 1'b1 ;  
 
	always @(posedge sys_CLK) begin        //6MHz
		if(counter6MHz == 4) begin
			counter6MHz = 0;
			clk_6MHz = ~clk_6MHz;
		end
		else begin
         counter6MHz = counter6MHz + 24'b1;
		end
	end
 
	always @(posedge sys_CLK) begin        //4Hz
		if(counter4Hz == 6250000) begin
			counter4Hz = 0;
         clk_4Hz = ~clk_4Hz;
		end
		else begin
         counter4Hz = counter4Hz + 24'b1;
		end
	end
 
	always @(posedge clk_6MHz) begin
		if(count == 16383) begin
         count = origin;
         audiof = ~audiof;
		end
		else begin
         count = count + 14'b1;
		end
	end
 
	always @(posedge clk_4Hz)  begin
		case(j)
			'd1:origin = 'd4916;  //low
			'd2:origin = 'd6168;
			'd3:origin = 'd7281;
			'd4:origin = 'd7791;
			'd5:origin = 'd8730;
			'd6:origin = 'd9565;
			'd7:origin = 'd10310;
			'd8:origin = 'd010647;  //middle
			'd9:origin = 'd011272;
			'd10:origin = 'd011831;
			'd11:origin = 'd012087;
			'd12:origin = 'd012556;
			'd13:origin = 'd012974;
			'd14:origin = 'd013346;
			'd15:origin = 'd13516;  //high
			'd16:origin = 'd13829;
			'd17:origin = 'd14108;
			'd18:origin = 'd11535;
			'd19:origin = 'd14470;
			'd20:origin = 'd14678;
			'd21:origin = 'd14864;
			
			default:origin = 'd011111;
		endcase             
	end
 
	always @(posedge clk_4Hz) begin
		if(len == 63)
         len = 0;
		else
         len = len + 8'b1;
		case(len)
			0:j = 1;
			1:j = 2;
			2:j = 3;
			3:j = 4;
			4:j = 5;
			5:j = 6;
			6:j = 7;
			7:j = 8;
			8:j = 9;
			9:j = 10;
			10:j = 11;
			11:j = 12;
			12:j = 13;
			13:j = 14;
			14:j = 15;
			15:j = 16;
			16:j = 17;
			17:j = 18;
			18:j = 19;
			19:j = 20;
			20:j = 21;
			21:j = 19;
			22:j = 17;
			23:j = 15;
			24:j = 13;
			25:j = 11;
			26:j = 9;
			27:j = 7;
			28:j = 5;
			29:j = 3;
			30:j = 1;
			default: j = 1;
		endcase                 
	end
endmodule
